package easier.app.x.starter;

import android.app.Activity;
import android.app.Application;
import android.app.Application.ActivityLifecycleCallbacks;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 记录activity启动顺序
 *
 * @author Liujin 2019/5/10:12:19:08
 */
public class ActivityTaskManager {

    /**
     * 所有任务,和启动顺序一致
     */
    private final LinkedList< TaskInfo > TASKS = new LinkedList<>();
    private final AtomicInteger mVisible = new AtomicInteger();

    /**
     * @param app 注册监听
     */
    public void register( Application app ) {

        app.registerActivityLifecycleCallbacks( new ActivityLifecycleCallbacks() {

            @Override
            public void onActivityCreated( Activity activity, Bundle savedInstanceState ) {

                addToTask( activity );
            }

            @Override
            public void onActivityStarted( Activity activity ) {

                mVisible.addAndGet( 1 );
            }

            @Override
            public void onActivityResumed( Activity activity ) {

                sequence( activity );
            }

            @Override
            public void onActivityPaused( Activity activity ) {

            }

            @Override
            public void onActivityStopped( Activity activity ) {

                mVisible.addAndGet( -1 );
            }

            @Override
            public void onActivitySaveInstanceState( Activity activity, Bundle outState ) {

            }

            @Override
            public void onActivityDestroyed( Activity activity ) {

                removeTask( activity );
            }
        } );
    }

    /**
     * @param activity 排序任务组
     */
    private void sequence( Activity activity ) {

        int taskId = activity.getTaskId();
        Iterator< TaskInfo > iterator = TASKS.iterator();
        while ( iterator.hasNext() ) {
            TaskInfo info = iterator.next();
            if ( info.mTaskId == taskId ) {
                iterator.remove();
                TASKS.addFirst( info );
                return;
            }
        }
    }

    /**
     * @param activity 删除任务
     */
    private void removeTask( Activity activity ) {

        int taskId = activity.getTaskId();
        Iterator< TaskInfo > iterator = TASKS.iterator();
        while ( iterator.hasNext() ) {
            TaskInfo info = iterator.next();
            if ( info.mTaskId == taskId ) {
                LinkedList< Activity > list = info.mActivities;
                list.remove( activity );
                if ( list.isEmpty() ) {
                    iterator.remove();
                }
                return;
            }
        }
    }

    /**
     * @param activity 添加任务
     */
    private void addToTask( Activity activity ) {

        int taskId = activity.getTaskId();
        for ( TaskInfo task : TASKS ) {
            if ( task.mTaskId == taskId ) {
                task.mActivities.addFirst( activity );
                return;
            }
        }

        // 还没有该任务栈
        TaskInfo taskInfo = new TaskInfo();
        taskInfo.mTaskId = taskId;
        TASKS.addFirst( taskInfo );
        taskInfo.mActivities.addFirst( activity );
    }

    /**
     * @return 获取所有任务组的string标识
     */
    public String getString() {

        StringBuilder result = new StringBuilder();
        for ( TaskInfo task : TASKS ) {
            result.append( task.toString() ).append( '\n' );
        }
        return result.toString();
    }

    /**
     * @return 当前activity数量
     */
    public int count() {

        int result = 0;
        for ( TaskInfo task : TASKS ) {
            result += task.mActivities.size();
        }
        return result;
    }

    /**
     * @param container 当前activity排序
     */
    public void currentActivities( List< Activity > container ) {

        container.clear();
        for ( TaskInfo task : TASKS ) {
            container.addAll( task.mActivities );
        }
    }

    /**
     * 当前activity
     */
    @Nullable
    public Activity currentActivity() {

        try {
            return TASKS.get( 0 ).mActivities.get( 0 );
        } catch ( Exception e ) {
            return null;
        }
    }

    /**
     * 结束所有Activity
     */
    public void finishAll() {

        for ( int i = 0, tasksSize = TASKS.size(); i < tasksSize; i++ ) {
            TaskInfo task = TASKS.get( i );
            LinkedList< Activity > activities = task.mActivities;
            for ( Activity activity : activities ) {
                //activity.overridePendingTransition( 0, 0 );
                activity.finish();
            }
        }
    }

    /**
     * @return 获取可见Activity数量
     */
    public int getVisible() {

        return mVisible.get();
    }

    /**
     * 单个任务栈,保存任务ID和该id下所有任务
     */
    private static class TaskInfo {

        private int mTaskId;
        private final LinkedList< Activity > mActivities = new LinkedList<>();

        @NonNull
        @Override
        public String toString() {

            StringBuilder builder = new StringBuilder();
            builder.append( "TaskId:" ).append( mTaskId ).append( '\n' );
            for ( Activity activity : mActivities ) {
                builder.append( '\t' ).append( activity ).append( '\n' );
            }
            return builder.toString();
        }
    }
}
